<template>
	<view class="big-box">
		<view class="box-header-all">
			<view class="box-header">MBTI测试</view>
			<u-icon name="list-dot" color="#2979ff" size="28" class="icon" @click="jumpToUnanswered"></u-icon>
		</view>
		<view class="box2">
			<view class="div2">
				<view class="question-progress">
					{{p}}<text class="question-total"> /{{ Data.total }}</text>
				</view>
				<view class="div3">
					<view class="auto-next-text">自动跳转下一题</view>
					<u-switch size="25" v-model="value"></u-switch>
				</view>
			</view>
			<view class="div4">
				<view class="question-text" v-if="Data.rows[id]">{{Data.rows[id].content}}</view>
				<view class="options-box">
					<view class="option-item1" :class="{ selected: selectedOptions[id] === 3 }" @click="select(3)">A.
						非常符合</view>
					<view class="option-item1" :class="{ selected: selectedOptions[id] === 2 }" @click="select(2)">B.
						符合</view>
					<view class="option-item1" :class="{ selected: selectedOptions[id] === 1 }" @click="select(1)">C.
						不符合</view>
					<view class="option-item1" :class="{ selected: selectedOptions[id] === 0 }" @click="select(0)">D.
						非常不符</view>
				</view>
			</view>
			<view class="div6" @click="unclick(2)" v-show="id>0">
				<u-icon name="arrow-left" size="20" color="#9013BC"></u-icon>
				<text class="prev-text">上一题</text>
			</view>
			<view class="btn-box">
				<button class="button1" @click="unclick(1)">{{text}}</button>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		getMbtiTest,
		insertOrUpdateResult
	} from '../../../api/mentalTest/mbtiTest.js';
	import {
		insterTestList
	} from '../../../api/mentalTest/testList';
	import {
		getAIText
	} from '../../../api/mentalTest/mentalTestAi.js';
	export default {
		props: {
			text: String,
		},
		data() {
			return {
				selectedOptions: {},
				id: 0,
				p: 1,
				text: "下一题",
				ResultMap: null,
				value: true,
				answerMap: {}, // 新增：用于记录每题是否已答
				startingTime: 0, // 记录当前时间
				endingTime: 0, // 记录结束时间
				startDate: null,
				duringTime: 0,
				isSubmit: true,
				testId: null,
				dateResult: {
					type: null,
					startTime: "",
					during: "",
					address: "秦皇岛市",
					nickName: "张三",
					aiText: ""
				},
				storageData: {},

				Data: {
					rows: [],
					total: 0
				},
				mbtiStatus: { // mbti测试状态
					id: 1,
					testStatus: 0, // 是否提交
					isSubmitFirst: false
				}
			}
		},
		onLoad(option) {
			this.isSubmit = option.isExist === 'false' ? false : true
			this.testId = option.id
			console.log("isSubmit", this.isSubmit)
		},
		onShow() {
			getMbtiTest().then(res => {
				this.Data = res;
			})
			this.ResultMap = new Map();
			this.ResultMap.set("E", 0)
			this.ResultMap.set("I", 0)
			this.ResultMap.set("P", 0)
			this.ResultMap.set("J", 0)
			this.ResultMap.set("T", 0)
			this.ResultMap.set("F", 0)
			this.ResultMap.set("S", 0)
			this.ResultMap.set("N", 0)
			// 选择题对应的分数  this.ResultMap.set( data[0].type  ,  新分数)    计算分数
			// 获得时间戳	
			this.date = new Date();
			this.startingTime = this.date.getTime();
			this.startDate = this.date;
			// 转日期
			this.dateResult.startTime = this.formatDate(this.date);
			console.log(this.dateResult.startTime);
			// 判断是否为重新测试
		},

		methods: {
			jumpToUnanswered() {
				const firstUnanswered = this.checkAllAnswered();
				if (firstUnanswered !== -1) {
					uni.showToast({
						title: `跳转到第 ${firstUnanswered + 1} 题`,
						icon: 'none'
					});
					this.id = firstUnanswered;
					this.p = firstUnanswered + 1;
				} else {
					uni.showToast({
						title: '全部已答完',
						icon: 'success'
					});
				}
			},
			// 已答题数统计（用于提示剩余多少题）
			answeredCount() {
				return Object.keys(this.selectedOptions).length;
			},
			//查看有没有未答的题 并跳转到未答题的页面
			checkAllAnswered() {
				let totalQuestions = this.Data.total;
				for (let i = 0; i < totalQuestions; i++) {
					if (this.selectedOptions[i] === undefined) {
						return i; // 返回第一道未答题的索引
					}
				}
				return -1; // 全部已答
			},
			getTimeDifferenceStr(date1, date2) {
				const diffMs = Math.abs(date2 - date1); // 获取时间差（毫秒）
				const totalSeconds = Math.floor(diffMs / 1000);
				const hours = Math.floor(totalSeconds / 3600);
				const minutes = Math.floor((totalSeconds % 3600) / 60);
				const seconds = totalSeconds % 60;
				let result = '';
				if (hours > 0) result += `${hours}小时`;
				if (minutes > 0) result += `${minutes}分`;
				if (seconds > 0 || result === '') result += `${seconds}秒`; // 如果前面都为0，也显示秒
				return result;
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需+1 
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}`;
			}, // 示例用法const date = new Date(); // 当前时间console.log(formatDate(date)); // 输出类似 2023-09-30 15:05
			select(score) {

				const currentId = this.id;
				const currentType = this.Data.rows[currentId].dimension;

				// 获取当前题目的旧分数（如果答过）
				const oldScore = this.answerMap[currentId];
				// 如果答过，需要先减去旧分数
				if (oldScore !== undefined) {
					this.ResultMap.set(currentType, this.ResultMap.get(currentType) - oldScore);
				}
				// 设置新分数
				this.$set(this.selectedOptions, currentId, score);
				this.$set(this.answerMap, currentId, score);
				// 加上新分数
				this.ResultMap.set(currentType, this.ResultMap.get(currentType) + score);
				console.log(this.ResultMap);
				// 如果开启了自动跳转
				if (this.value) {
					// 延时跳转开始
					setTimeout(() => {
						this.unclick(1);
					}, 500); // 延时 300 毫秒（0.3秒）
				}
			},
			unclick(e) {
				if (this.id <= this.Data.total - 1) {
					if (e === 1) {
						this.id = this.id + 1
						if (this.id < this.Data.total) {
							this.p = this.p + 1
						}
						if (this.id == this.Data.total - 1) {
							this.text = "提交"
						}
						if (this.id == this.Data.total) {
							this.id = this.id - 1;
							this.date = new Date() // 获得结束日期
							this.endingTime = this.date.getTime();
							this.duringTime = this.endingTime - this.startingTime; // 用时多长
							console.log(this.duringTime);
							this.checkAndSubmit();
							return;
						}
					} else if (e === 2) {
						this.text = "下一题"
						this.id = this.id - 1
						this.p = this.p - 1
					}
				}
			},
			//有题未答完功能
			checkAndSubmit() {
				const firstUnanswered = this.checkAllAnswered();
				if (firstUnanswered !== -1) {
					uni.showModal({
						title: '提示',
						content: `还有 ${this.Data.total - this.answeredCount()} 题未答，是否继续提交？`,
						showCancel: true,
						confirmText: '继续提交',
						cancelText: '查看未答',
						success: (res) => {
							if (res.confirm) {
								this.submitAnswer();
							} else {
								this.id = firstUnanswered;
								this.p = firstUnanswered + 1;
								this.text = "下一题"
							}
						}
					});
				} else {
					this.submitAnswer();
				}
			},
			//提交答案代码
			submitAnswer() {
				// 获取当前时间，记录答题结束时间
				this.date = new Date();
				this.endingTime = this.date.getTime();
				// 计算答题总时长（单位：毫秒）
				this.duringTime = this.endingTime - this.startingTime;
				// 设置最短答题时间为 5 分钟（300000 毫秒）
				const MIN_DURATION = 5 * 60 * 1000;
				// 判断用户是否已答题至少 5 分钟
				if (this.duringTime >= MIN_DURATION) {
					// 计算并格式化答题时长（例如：5分30秒）
					this.dateResult.during = this.getTimeDifferenceStr(this.startDate, new Date());
					// 将结果映射表（ResultMap）转换为对象并赋值给 dateResult.type
					this.dateResult.type = Object.fromEntries(this.ResultMap);

					// 如果当前还未提交（防止重复提交）
					if (!this.isSubmit) {
						// 调用接口，将当前测试标记为已提交
						insterTestList(this.testId).then(res => {
							console.log("提交成功", res);
						});

						if (true) {
							// 构建用于保存到数据库的结果对象，包括每个维度的得分字段
							this.storageData = {
								...this.dateResult, // 展开所有结果字段（包括 during 和 type）
								e: this.dateResult.type.E, // E 外向
								i: this.dateResult.type.I, // I 内向
								f: this.dateResult.type.F, // F 情感
								t: this.dateResult.type.T, // T 思考
								p: this.dateResult.type.P, // P 感知
								j: this.dateResult.type.J, // J 判断
								s: this.dateResult.type.S, // S 实感
								n: this.dateResult.type.N // N 直觉
							}

							// 因为各维度分值已单独提取，清除原始的 type 对象字段（避免重复或存储问题）
							this.storageData.type = null;

							// 调用接口，插入或更新当前用户的测试结果（保存到后端数据库）
							insertOrUpdateResult(this.storageData);

							// 将每个维度的得分拼接为字符串，形如 "E:20 I:10 F:16 T:14 ..."
							const type = Object.entries(this.dateResult.type)
								.map(([key, value]) => `${key}:${value}`)
								.join(' ');

							// 构造面向 AI 问答的 prompt，让 AI 根据 MBTI 结果分析人格与职业建议
							let questionAi = "我通过测试mbti后，" + type + "请问我是什么人格类型？有什么特定？适合什么职业？"

							// 跳转至测试结果展示页面，并通过 URL 参数传递测试数据、是否提交状态、AI 问题文本和测试 ID
							uni.redirectTo({
								url: "/pages/careerModel/careerResult/mbtiTestResults/mbtiTestResults" +
									"?data=" + encodeURIComponent(JSON.stringify(this.dateResult)) + // 测试结果数据
									"&isSubmit=" + this.isSubmit + // 是否是提交状态
									"&questionAi=" + questionAi + // AI 问题 prompt
									"&testId=" + this.testId // 当前测试的 ID
							})
						}
					}

					// 重定向跳转到 MBTI 测试结果页面，并传递结果数据
					uni.redirectTo({
						url: "/pages/careerModel/careerResult/mbtiTestResults/mbtiTestResults?data=" +
							encodeURIComponent(JSON.stringify(this.dateResult))
					});

				} else {
					// 如果答题时长不足 5 分钟，计算还需要等待的分钟数（向上取整）
					const remainMinute = Math.ceil((MIN_DURATION - this.duringTime) / 60000);

					// 弹出提示，提醒用户继续答题
					uni.showToast({
						title: `答题时间不足5分钟，请在 ${remainMinute} 分钟后提交`,
						icon: 'none',
						duration: 3000
					});
				}
			},
		}
	}
</script>
<style>
	.big-box {
		width: 100%;
		min-height: 100vh;
		background-color: #f2f2f2;
		display: flex;
		flex-direction: column;
	}

	.box-header-all {
		display: flex;
		background-color: #fff;
		padding: 20rpx 30rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		animation: facein 0.5s ease-out;

	}

	.box-header {
		margin: 0 245rpx;
		font-size: 32rpx;
		font-weight: 700;
		color: #333;
	}

	.box2 {
		background-color: #ffffff;
		border-radius: 20rpx;
		margin: 30rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		animation: facein 0.5s ease-out;
	}

	.div2 {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.question-progress {
		color: #9013bc;
		font-size: 30rpx;
		font-weight: 700;
	}

	.question-total {
		color: #999;
		font-size: 24rpx;
		font-weight: 500;
		margin-left: 6rpx;
	}

	.div3 {
		display: flex;
		align-items: center;
		gap: 10rpx;
	}

	.auto-next-text {
		font-size: 28rpx;
		color: #999;
	}

	.div4 {
		border-top: 2rpx solid #f2f2f2;
		padding-top: 30rpx;
	}

	.question-text {
		font-size: 30rpx;
		color: #333;
		font-weight: 600;
		margin-bottom: 40rpx;
	}

	.options-box {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.option-item1 {
		padding: 25rpx 30rpx;
		font-size: 28rpx;
		color: #333;
		border-bottom: 3rpx solid #f2f2f2;
		border-radius: 10px;
		transition: all 0.3s ease-in-out;
	}

	.option-item1.selected {
		background-color: #d7ebff !important;
		color: #169BD5 !important;
		font-weight: bold;
		border: 2rpx solid #169BD5 !important;
		transform: scale(1.02) !important;
	}

	.div6 {
		display: flex;
		align-items: center;
		color: #9013BC;
		margin-top: 40rpx;
	}

	.prev-text {
		margin-left: 10rpx;
		font-size: 28rpx;
		width: 100%;
		border-bottom: 3rpx solid #f2f2f2;
	}

	.btn-box {
		margin-top: 40rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.button1 {
		width: 80%;
		height: 60rpx;
		background-color: #169BD5;
		color: white;
		font-size: 30rpx;
		border-radius: 50rpx;
		text-align: center;
		padding-bottom: 75rpx;
		transition: background-color 0.3s ease-in-out, transform 0.3s ease;
	}

	.button1:hover {
		transition: 0.5s ease-out;
		transform: scale(1.05);
	}

	.button2 {
		width: 20%;
		height: 60rpx;
		background-color: #169BD5;
		color: white;
		font-size: 30rpx;
		border-radius: 50rpx;
		text-align: center;
		padding-bottom: 75rpx;
	}

	@keyframes facein {
		from {
			opacity: 0;
			transform: scale(0.9);
		}

		to {
			opacity: 1;
			transform: scale(1);
		}
	}

	.selected {
		background-color: #d7ebff;
		color: #169BD5;
		font-weight: bold;
		border: 2rpx solid #169BD5;
	}
</style>